package com.guigu.controller;


import com.guigu.pojo.*;
import com.guigu.service.PayDetailsService;
import com.guigu.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 出库单明细表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@RestController
@RequestMapping("/pay-details")
public class PayDetailsController {

    @Autowired
    private PayDetailsService payDetailsService;

    @Autowired
    private PayService payService;

    @GetMapping("/{payId}")
    @ResponseBody
    public List<PayDetails> getProductDetails(@PathVariable Integer payId) {
        List<PayDetails> payDetails = payDetailsService.getPayDetails(payId);

        System.out.println(payDetails);
        return payDetails;
    }

    @PostMapping("/pay")
    @ResponseBody
    public Boolean savePay(@RequestBody Orders order) {
        System.out.println(order);
        try {
            Pay pay = new Pay();
            // 生成订单号
            long orderNoLong = getOrderNo();  // long 类型订单号
            String orderNoString = String.valueOf(orderNoLong);  // 转换为 String 类型存储在数据库
            pay.setPayOrderNumber(orderNoString);
            pay.setStockId(1);
            pay.setPayer("管理员");

            Integer TotalAmount = order.getOrderDetails().stream()
                    .mapToInt(OrderDetails::getAmount)
                    .sum();
            pay.setTotalAmount(TotalAmount);
            pay.setTotalPrice(order.getTotalPrice());
            pay.setOrderList(order.getOrderNumber());
            pay.setRegister("管理员");
            pay.setRegisterTime(new Date());
            payService.save(pay);
            for (OrderDetails orderDetail : order.getOrderDetails()) {
                PayDetails payDetails = new PayDetails();
                payDetails.setStockId(1);
                payDetails.setPayId(pay.getPayId());
                payDetails.setProductId(orderDetail.getProductId());
                payDetails.setAmount(orderDetail.getAmount());
                payDetails.setPrice(orderDetail.getPrice());
                payDetails.setSubTotal(orderDetail.getSubtotal());
                payDetailsService.save(payDetails);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    // 生成订单号（long 类型）
    private static String date;
    private static long orderNum = 0L;

    public static synchronized long getOrderNo() {
        String str = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        if (date == null || !date.equals(str)) {
            date = str;
            orderNum = 0L;
        }
        orderNum++;
        long orderNO = Long.parseLong(date) * 10000;
        orderNO += orderNum;
        return orderNO;  // 返回 long 类型订单号
    }
}

